package com.bootx.event;

import com.bootx.service.RedPackageInfoService;
import com.bootx.service.RedisService;
import jakarta.annotation.PostConstruct;
import jakarta.annotation.PreDestroy;
import jakarta.annotation.Resource;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.nio.file.*;
import java.nio.file.attribute.BasicFileAttributes;

import static java.nio.file.StandardWatchEventKinds.ENTRY_CREATE;

/**
 * @author black
 */ //@Service
public class DirectoryWatchService {
    @Resource
    private RedPackageInfoService redPackageInfoService;
    private final FileWatchProperties fileWatchProperties;
    private WatchService watchService;
    private Thread watchThread;
    private boolean running = true;
    @Resource
    private RedisService redisService;

    public DirectoryWatchService(FileWatchProperties fileWatchProperties) {
        this.fileWatchProperties = fileWatchProperties;
    }

    @PostConstruct
    public void init() {
        try {
            Path path = Paths.get(fileWatchProperties.getDirectory());
            if (!Files.exists(path) || !Files.isDirectory(path)) {

                boolean mkdir = path.toFile().mkdir();
                if(mkdir){
                    System.out.println(path.toAbsolutePath()+":创建成功");
                }else{
                    System.out.println(path.toAbsolutePath()+":创建失败");
                }
            }

            watchService = FileSystems.getDefault().newWatchService();
            path.register(watchService, ENTRY_CREATE);
            watchThread = new Thread(() -> processEvents(path), "watch-thread");
            watchThread.start();

        } catch (IOException e) {

        }
    }

    private void processEvents(Path watchPath) {
        while (running) {
            WatchKey key;
            try {
                key = watchService.take();
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
                break;
            }

            for (WatchEvent<?> event : key.pollEvents()) {
                if (event.kind() == ENTRY_CREATE) {
                    Path fileName = (Path) event.context();
                    Path fullPath = watchPath.resolve(fileName);
                    handleNewFile(fullPath);
                }
            }

            boolean valid = key.reset();
            if (!valid) {
                System.out.println("⚠️ 监听器失效");
                break;
            }
        }
    }

    private void handleNewFile(Path path) {
        redPackageInfoService.create(path);
    }


    @PreDestroy
    public void shutdown() {
        running = false;
        try {
            if (watchService != null) {
                watchService.close();
            }
            System.out.println("🛑 监听器已关闭");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
